<template>
  <div class="user-works">
    <div class="page-header">
      <h1>AI社区作品管理</h1>
      <p>管理用户在AI社区发布的作品，支持查看、删除和状态控制</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon">
                <el-icon size="24" color="#409EFF"><Picture /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ formatNumber(stats.totalWorks) }}</div>
                <div class="stat-label">总作品数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon">
                <el-icon size="24" color="#67C23A"><View /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ formatNumber(stats.publicWorks) }}</div>
                <div class="stat-label">已审核通过</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon">
                <el-icon size="24" color="#E6A23C"><Star /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ formatNumber(stats.totalLikes) }}</div>
                <div class="stat-label">总点赞数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon">
                <el-icon size="24" color="#F56C6C"><View /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ formatNumber(stats.totalViews) }}</div>
                <div class="stat-label">总浏览数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon">
                <el-icon size="24" color="#909399"><Calendar /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ formatNumber(stats.todayWorks) }}</div>
                <div class="stat-label">今日新增</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon">
                <el-icon size="24" color="#606266"><TrendCharts /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ formatNumber(stats.monthWorks) }}</div>
                <div class="stat-label">本月新增</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 作品管理列表 -->
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span>作品列表</span>
          <div class="card-header-actions">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索标题/提示词"
              style="width: 200px; margin-right: 10px;"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select
              v-model="searchForm.status"
              placeholder="状态筛选"
              style="width: 120px; margin-right: 10px;"
              clearable
              @change="handleSearch"
            >
              <el-option label="全部" value="" />
              <el-option label="显示" value="1" />
              <el-option label="隐藏" value="0" />
            </el-select>
            <el-select
              v-model="searchForm.isPublic"
              placeholder="审核状态"
              style="width: 120px; margin-right: 10px;"
              clearable
              @change="handleSearch"
            >
              <el-option label="全部" value="" />
              <el-option label="已通过" value="1" />
              <el-option label="待审核" value="0" />
            </el-select>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="作品标题" min-width="150" show-overflow-tooltip />
        <el-table-column label="预览图" width="100">
          <template #default="{ row }">
            <div v-if="row.imageUrl" class="image-preview">
              <el-image
                :src="row.imageUrl"
                style="width: 60px; height: 60px; border-radius: 4px;"
                fit="cover"
                :preview-src-list="[row.imageUrl]"
                loading="lazy"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon size="20" color="#C0C4CC"><Picture /></el-icon>
                    <div class="error-text">图片缺失</div>
                  </div>
                </template>
              </el-image>
            </div>
            <div v-else class="no-image">
              <el-icon size="20" color="#E4E7ED"><Picture /></el-icon>
              <div class="no-image-text">暂无图片</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="prompt" label="生成提示词" min-width="200" show-overflow-tooltip />
        <el-table-column prop="userId" label="用户ID" width="100" />
        <el-table-column prop="style" label="风格" width="100" show-overflow-tooltip />
        <el-table-column prop="size" label="尺寸" width="100" />
        <el-table-column label="互动数据" width="120">
          <template #default="{ row }">
            <div class="interaction-data">
              <div><el-icon size="14"><View /></el-icon> {{ row.viewCount || 0 }}</div>
              <div><el-icon size="14"><Star /></el-icon> {{ row.likeCount || 0 }}</div>
              <div><el-icon size="14"><ChatDotRound /></el-icon> {{ row.commentCount || 0 }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isPublic" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getReviewType(row.isPublic)">
              {{ getReviewText(row.isPublic) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" sortable="custom">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.imageUrl"
              type="primary"
              size="small"
              @click="viewImage(row.imageUrl)"
            >
              查看图片
            </el-button>
            <el-button
              v-else
              type="info"
              size="small"
              disabled
            >
              无图片
            </el-button>
            <el-button
              :type="row.status === 1 ? 'warning' : 'success'"
              size="small"
              @click="toggleStatus(row)"
            >
              {{ row.status === 1 ? '隐藏' : '显示' }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deleteWork(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <!-- 自定义分页控件 -->
        <div class="custom-pagination">
          <div class="pagination-info">
            <span>共 {{ pagination.total }} 条记录</span>
            <span style="margin-left: 20px;">
              每页显示
              <el-select 
                v-model="pagination.size" 
                @change="handlePageSizeChange"
                style="width: 80px; margin: 0 8px;"
                size="small"
              >
                <el-option label="10" :value="10" />
                <el-option label="20" :value="20" />
                <el-option label="50" :value="50" />
                <el-option label="100" :value="100" />
              </el-select>
              条
            </span>
          </div>
          
          <div class="pagination-controls">
            <el-button 
              size="small" 
              :disabled="pagination.current <= 1"
              @click="goToPage(1)"
            >
              首页
            </el-button>
            <el-button 
              size="small" 
              :disabled="pagination.current <= 1"
              @click="goToPage(pagination.current - 1)"
            >
              上一页
            </el-button>
            
            <!-- 页码按钮 -->
            <template v-for="page in getPageNumbers()" :key="page">
              <el-button 
                v-if="page !== '...'"
                size="small"
                :type="page === pagination.current ? 'primary' : 'default'"
                @click="goToPage(page as number)"
              >
                {{ page }}
              </el-button>
              <span v-else style="margin: 0 8px;">...</span>
            </template>
            
            <el-button 
              size="small" 
              :disabled="pagination.current >= totalPages"
              @click="goToPage(pagination.current + 1)"
            >
              下一页
            </el-button>
            <el-button 
              size="small" 
              :disabled="pagination.current >= totalPages"
              @click="goToPage(totalPages)"
            >
              末页
            </el-button>
            
            <span style="margin-left: 20px;">
              跳至
              <el-input 
                v-model="jumpPage" 
                @keyup.enter="handleJumpToPage"
                style="width: 60px; margin: 0 8px;"
                size="small"
              />
              页
            </span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="imagePreviewVisible" title="图片预览" width="60%">
      <div style="text-align: center;">
        <img :src="previewImageUrl" style="max-width: 100%; max-height: 600px;" alt="用户作品" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Picture, View, Star, Calendar, TrendCharts, Search, 
  ChatDotRound 
} from '@element-plus/icons-vue'
import { getUserWorkStats, getUserWorkList, deleteUserWork, updateUserWorkStatus } from '@/api'

// 响应式数据
const loading = ref(false)
const stats = ref({
  totalWorks: 0,
  publicWorks: 0,
  totalLikes: 0,
  totalViews: 0,
  todayWorks: 0,
  monthWorks: 0,
  activeWorks: 0
})

const searchForm = reactive({
  keyword: '',
  status: '',
  isPublic: ''
})

const pagination = ref({
  current: 1,
  size: 20,
  total: 0
})

const tableData = ref([])
const imagePreviewVisible = ref(false)
const previewImageUrl = ref('')
const jumpPage = ref('')

// 计算属性
const totalPages = computed(() => {
  return Math.ceil(pagination.value.total / pagination.value.size)
})

// 方法
const formatNumber = (num: number) => {
  return num.toLocaleString()
}

const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

const getStatusType = (status: number) => {
  return status === 1 ? 'success' : 'danger'
}

const getStatusText = (status: number) => {
  return status === 1 ? '显示' : '隐藏'
}

const getReviewType = (reviewStatus: number) => {
  switch (reviewStatus) {
    case 1: return 'success'   // 审核通过
    case 2: return 'danger'    // 审核拒绝
    default: return 'warning'  // 待审核
  }
}

const getReviewText = (reviewStatus: number) => {
  switch (reviewStatus) {
    case 1: return '已通过'
    case 2: return '已拒绝'
    default: return '待审核'
  }
}

const loadStats = async () => {
  try {
    console.log('正在加载用户作品统计数据...')
    const response = await getUserWorkStats()
    console.log('用户作品统计API响应:', response)
    
    if (response && response.success) {
      console.log('用户作品统计数据:', response.data)
      stats.value = response.data
    } else {
      console.error('API返回失败:', response)
      ElMessage.error('获取统计数据失败: ' + (response?.message || '未知错误'))
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('加载统计数据失败: ' + (error as Error).message)
  }
}

const loadWorksData = async () => {
  console.log('=== loadWorksData 开始执行 ===')
  loading.value = true
  try {
    // 过滤掉 undefined 值
    const params: any = {
      current: pagination.value.current,
      size: pagination.value.size
    }
    
    if (searchForm.keyword) {
      params.keyword = searchForm.keyword
    }
    
    if (searchForm.status) {
      params.status = searchForm.status
    }
    
    if (searchForm.isPublic) {
      params.isPublic = searchForm.isPublic
    }
    
    console.log('正在加载用户作品数据...', params)
    console.log('API URL将是:', '/api/admin/user-works')
    
    const response = await getUserWorkList(params)
    console.log('用户作品列表API响应:', response)
    
    if (response && response.success) {
      console.log('用户作品数据:', response.data)
      
      const pageResult = response.data
      tableData.value = pageResult.data || []
      pagination.value.total = Number(pageResult.total) || 0
      pagination.value.current = Number(pageResult.current) || pagination.value.current
      pagination.value.size = Number(pageResult.size) || pagination.value.size
      
      console.log('设置分页信息: total=', pagination.value.total, ', current=', pagination.value.current, ', size=', pagination.value.size)
      console.log('表格数据条数:', tableData.value.length)
      
      // 检查图片URL状态
      console.log('加载了', tableData.value.length, '个作品，其中有效图片：', 
        tableData.value.filter(work => work.imageUrl && work.imageUrl !== 'INVALID_URL').length, '个')
      
    } else {
      console.error('用户作品列表API返回失败:', response)
      ElMessage.error('获取作品列表失败: ' + (response?.message || '未知错误'))
    }
  } catch (error) {
    console.error('=== loadWorksData 发生错误 ===')
    console.error('错误详情:', error)
    console.error('错误类型:', typeof error)
    console.error('错误信息:', (error as any)?.message || '无详细信息')
    console.error('完整错误对象:', JSON.stringify(error, null, 2))
    ElMessage.error('加载作品数据失败: ' + (error as Error).message)
  } finally {
    console.log('=== loadWorksData 执行完成 ===')
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.value.current = 1
  loadWorksData()
}

// 自定义分页控制方法
const goToPage = async (page: number) => {
  if (page < 1 || page > totalPages.value) {
    ElMessage.warning(`页码超出范围，请输入1-${totalPages.value}之间的数字`)
    return
  }
  
  if (page === pagination.value.current) {
    return
  }
  
  pagination.value.current = page
  await loadWorksData()
}

const handlePageSizeChange = async (newSize: number) => {
  console.log('页面大小变化:', pagination.value.size, '→', newSize)
  
  pagination.value.current = 1
  pagination.value.size = newSize
  await loadWorksData()
  
  ElMessage.success(`页面大小已切换到${newSize}条/页`)
}

const handleJumpToPage = () => {
  const page = parseInt(jumpPage.value)
  if (isNaN(page)) {
    ElMessage.warning('请输入有效的页码')
    return
  }
  goToPage(page)
  jumpPage.value = ''
}

const getPageNumbers = () => {
  const total = totalPages.value
  const current = pagination.value.current
  const delta = 2 // 当前页前后显示的页数
  
  if (total <= 7) {
    // 总页数小于等于7，显示所有页码
    return Array.from({ length: total }, (_, i) => i + 1)
  }
  
  const pages: (number | string)[] = []
  
  // 始终显示第1页
  pages.push(1)
  
  if (current - delta > 2) {
    pages.push('...')
  }
  
  // 显示当前页附近的页码
  for (let i = Math.max(2, current - delta); i <= Math.min(total - 1, current + delta); i++) {
    pages.push(i)
  }
  
  if (current + delta < total - 1) {
    pages.push('...')
  }
  
  // 始终显示最后一页
  if (total > 1) {
    pages.push(total)
  }
  
  return pages
}

const handleSortChange = ({ prop, order }: any) => {
  // 这里可以实现排序逻辑
  console.log('排序变化:', prop, order)
}

const viewImage = (imageUrl: string) => {
  // 检查图片是否可访问
  const img = new Image()
  img.onload = () => {
    previewImageUrl.value = imageUrl
    imagePreviewVisible.value = true
  }
  img.onerror = () => {
    ElMessage.warning('图片文件不存在或无法访问')
  }
  img.src = imageUrl
}

const toggleStatus = async (row: any) => {
  try {
    const newStatus = row.status === 1 ? 0 : 1
    const statusText = newStatus === 1 ? '显示' : '隐藏'
    
    await ElMessageBox.confirm(
      `确定要将作品"${row.title}"设为${statusText}状态吗？`,
      '状态切换确认', 
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await updateUserWorkStatus(row.id, newStatus)
    
    if (response && response.success) {
      ElMessage.success(`作品状态已切换为${statusText}`)
      // 重新加载数据
      await loadWorksData()
      await loadStats()
    } else {
      ElMessage.error('状态更新失败: ' + (response?.message || '未知错误'))
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('状态切换失败:', error)
      ElMessage.error('状态切换失败: ' + (error.message || '未知错误'))
    }
  }
}

const deleteWork = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除作品"${row.title}"吗？

作品详情：
• ID: ${row.id}
• 用户ID: ${row.userId}
• 标题: ${row.title}
• 提示词: ${row.prompt}

注意：删除后数据将无法恢复！`,
      '删除确认', 
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    )
    
    const loadingInstance = ElMessage({
      message: '正在删除作品...',
      type: 'info',
      duration: 0
    })
    
    try {
      const response = await deleteUserWork(row.id)
      
      loadingInstance.close()
      
      if (response && response.success) {
        ElMessage.success('作品删除成功！')
        // 重新加载数据
        await loadWorksData()
        await loadStats()
      } else {
        ElMessage.error('删除失败: ' + (response?.message || '未知错误'))
      }
    } catch (apiError) {
      loadingInstance.close()
      throw apiError
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败: ' + (error.message || '未知错误'))
    }
  }
}

// 生命周期
onMounted(() => {
  loadStats()
  loadWorksData()
})
</script>

<style scoped>
.user-works {
  padding: 0;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stat-icon {
  margin-right: 16px;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  background-color: rgba(64, 158, 255, 0.1);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.main-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header-actions {
  display: flex;
  align-items: center;
}

.interaction-data {
  font-size: 12px;
  color: #606266;
}

.interaction-data div {
  display: flex;
  align-items: center;
  margin-bottom: 2px;
}

.interaction-data .el-icon {
  margin-right: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.custom-pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.pagination-info {
  display: flex;
  align-items: center;
  color: #606266;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 图片相关样式 */
.image-preview {
  display: flex;
  justify-content: center;
  align-items: center;
}

.image-error,
.no-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  border-radius: 4px;
  background-color: #f5f7fa;
  border: 1px solid #ebeef5;
}

.error-text,
.no-image-text {
  font-size: 10px;
  color: #909399;
  margin-top: 2px;
  text-align: center;
}

.image-error {
  background-color: #fef0f0;
  border-color: #fde2e2;
}

.error-text {
  color: #f56c6c;
}

@media (max-width: 768px) {
  .custom-pagination {
    flex-direction: column;
    gap: 10px;
  }
  
  .pagination-controls {
    justify-content: center;
    flex-wrap: wrap;
  }
}
</style>
